package com.kma.summer2012.client.presenters.mainPage.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormPanel;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.DialogBoxFactory;
import com.kma.summer2012.client.events.SortByDateEvent;
import com.kma.summer2012.client.events.UpdateCellTableEvent;
import com.kma.summer2012.client.events.engineer.EngineerShowRequestEvent;
import com.kma.summer2012.client.events.engineer.ViewMapEvent;
import com.kma.summer2012.client.events.manager.EditPageEventManager;
import com.kma.summer2012.client.events.manager.ManageToolsEvent;
import com.kma.summer2012.client.events.manager.ManageWorksEvent;
import com.kma.summer2012.client.events.manager.ShowRequestManager;
import com.kma.summer2012.client.events.operator.EditPageEvent;
import com.kma.summer2012.client.events.operator.OperatorShowRequestEvent;
import com.kma.summer2012.client.events.request.CreateRequestEvent;
import com.kma.summer2012.client.events.request.ExportRequestEvent;
import com.kma.summer2012.client.events.request.RequestsSelectedEvent;
import com.kma.summer2012.client.presenters.header.HeaderPresenter;
import com.kma.summer2012.client.presenters.mainPage.ClosedRequestsPresenter;
import com.kma.summer2012.client.services.AbstractCallBack;
import com.kma.summer2012.client.services.request.CrumbsRequestService;
import com.kma.summer2012.client.view.mainPage.ClosedRequests;
import com.kma.summer2012.shared.model.UICrumbsRequest;
import com.kma.summer2012.shared.model.UICrumbsUser;

import java.util.Date;
import java.util.List;


/**
 * Created with IntelliJ IDEA.
 * User: EUGENE
 * Date: 2/13/13
 * Time: 12:37 AM
 * To change this template use File | Settings | File Templates.
 */
public class RightSideBarPresenter implements IRightSideBarPresenter {
    private Display display;
    private CrumbsEventBus eventBus = CrumbsEventBus.getInstance();
    private List<UICrumbsRequest> currentRequests = null;
    private Integer tableID;
    private DialogBox dialogBoxClosedRequests;

    public RightSideBarPresenter(Display display) {
        this.display = display;
        bind();

        //for import requests
        // this.display.getFileUpload().setName("upload");
        this.display.getFormPanel().setEncoding(FormPanel.ENCODING_MULTIPART);
        this.display.getFormPanel().setMethod(FormPanel.METHOD_POST);
        this.display.getFormPanel().setAction(GWT.getModuleBaseURL() + "CrumbsFileUpload");

    }

    private void bind() {
        eventBus.addHandler(RequestsSelectedEvent.getType(), new RequestsSelectedEvent.RequestSelectedEventHandler() {
            @Override
            public void onRequestsSelected(RequestsSelectedEvent event) {
                if (tableID.equals(event.tableID))
                    currentRequests = event.requests;
            }
        });


        this.showButtons();
        display.getCreateBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doCreate();
            }
        });
        display.getExportRequestsBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doExport();
            }
        });
        display.getFindRequestBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doFindRequest();
            }
        });
        display.getImportRequestBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doImport();
            }
        });
        display.getManageToolsBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doManageTools();
            }
        });
        display.getViewMapBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doViewMap();
            }
        });
        display.getManageWorksBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doManageWorks();
            }
        });
        display.getClosedRequestsBtn().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                doShowClosedRequests();
            }
        });

        display.getFormPanel().addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
            @Override
            public void onSubmitComplete(FormPanel.SubmitCompleteEvent event) {
                DialogBoxFactory.createMessageBox(event.getResults(),"Import");
                CrumbsEventBus.getInstance().fireEvent(new UpdateCellTableEvent(tableID));
            }
        });
        this.display.getDataPicker().addValueChangeHandler(new ValueChangeHandler<Date>() {
            @Override
            public void onValueChange(ValueChangeEvent<Date> dateValueChangeEvent) {
                onDateChanged(dateValueChangeEvent.getValue());
            }
        });


        eventBus.addHandler(EditPageEventManager.getType(), new EditPageEventManager.EditPageEventManagerHandler() {
            @Override
            public void onEditPageEvent(EditPageEventManager event, UICrumbsRequest request) {
                hideDialogBox();
            }
        });

        eventBus.addHandler(EditPageEvent.getType(), new EditPageEvent.EditPageEventHandler() {
            @Override
            public void onEditPageEvent(EditPageEvent event, UICrumbsRequest request) {
                hideDialogBox();
            }
        });

        eventBus.addHandler(EngineerShowRequestEvent.getType(), new EngineerShowRequestEvent.ManagerShowRequestEventHandler() {
            @Override
            public void onEngineerShowRequestEvent(EngineerShowRequestEvent event, UICrumbsRequest request) {
                hideDialogBox();
            }
        });
        eventBus.addHandler(ShowRequestManager.getType(), new ShowRequestManager.ShowRequestManagerHandler() {
            @Override
            public void onShowPageEvent(ShowRequestManager event, UICrumbsRequest request) {
                hideDialogBox();
            }
        });

    }

    private void hideDialogBox() {
        if (dialogBoxClosedRequests != null) {
            dialogBoxClosedRequests.hide();
        }
    }

    private void onDateChanged(Date date) {
        this.eventBus.fireEvent(new SortByDateEvent(date, this.tableID));
    }

    private void doCreate() {
        this.eventBus.fireEvent(new CreateRequestEvent());
    }

    private void doExport() {
        this.eventBus.fireEvent(new ExportRequestEvent(this.currentRequests));
    }

    private void doManageTools() {
        this.eventBus.fireEvent(new ManageToolsEvent());
    }

    private void doFindRequest() {

        if (!this.display.getRequestIdToFind().equals("") && isInteger(this.display.getRequestIdToFind())) {
            int id = Integer.parseInt(this.display.getRequestIdToFind());

            CrumbsRequestService.App.getInstance().getById(id, new AbstractCallBack<UICrumbsRequest>() {
                @Override
                public void onSuccess(UICrumbsRequest uiCrumbsRequest) {
                    if (uiCrumbsRequest != null) {
                        eventBus.fireEvent(new OperatorShowRequestEvent(uiCrumbsRequest));
                    } else {
                        Window.alert("No such request in the database");
                    }
                }
            });
        } else {
            Window.alert("Empty or wrong id to find");
        }
    }

    public static boolean isInteger(String s) {
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

    private void doImport() {

        try {
            String filename = this.display.getFileUpload().getFilename();
            if (filename.length() == 0) {
                DialogBoxFactory.createMessageBox("No File Specified!","Import");
            } else {
                    this.display.getFormPanel().submit();
            }

        } catch (Exception e) {
            Window.alert("Choose file first!");
        }
    }

    private void doViewMap() {
        this.eventBus.fireEvent(new ViewMapEvent());
    }

    private void doShowCalendar() {
        //todo
    }

    private void doManageWorks() {
        this.eventBus.fireEvent(new ManageWorksEvent());
    }

    private void showButtons() {
        String position = HeaderPresenter.getUser().getPosition();
        if (position.equals(UICrumbsUser.OPERATOR_POSITION)) {
            this.display.showCreateBtn(true);
            this.display.showFindRequestBtn(true);
            this.display.showExportRequestsBtn(false);
            this.display.showImportRequestBtn(false);
            this.display.showManageToolsBtn(false);
            this.display.showManageWorksBtn(false);
            this.display.showViewMapBtn(false);
            this.display.showFileUpload(false);
            this.display.showClosedRequestBtn(false);
        } else if (position.equals(UICrumbsUser.MANAGER_POSITION)) {
            this.display.showImportRequestBtn(true);
            this.display.showManageToolsBtn(true);
            this.display.showManageWorksBtn(true);
            this.display.showViewMapBtn(true);
            this.display.showCreateBtn(false);
            this.display.showExportRequestsBtn(false);
            this.display.showFindRequestBtn(false);
            this.display.showFileUpload(true);
            this.display.showClosedRequestBtn(true);
        } else if (position.equals(UICrumbsUser.ENGINEER_POSITION)) {
            this.display.showExportRequestsBtn(true);
            this.display.showFindRequestBtn(false);
            this.display.showImportRequestBtn(false);
            this.display.showManageToolsBtn(false);
            this.display.showManageWorksBtn(false);
            this.display.showViewMapBtn(false);
            this.display.showCreateBtn(false);
            this.display.showFileUpload(false);
            this.display.showClosedRequestBtn(false);
        }
    }


    @Override
    public void setTableID(Integer id) {
        this.tableID = id;
    }

    public void doShowClosedRequests() {
        if (this.dialogBoxClosedRequests == null) {
            ClosedRequests content = new ClosedRequests();
            new ClosedRequestsPresenter(content);
            dialogBoxClosedRequests = DialogBoxFactory.getDialogBox(content, "Closed Requests");
        }

        dialogBoxClosedRequests.center();
        dialogBoxClosedRequests.show();
    }


}
